package cc.rengu.oltp.utility.util;

import java.security.SecureRandom;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

/**
 * 随机数工具类
 * Created by 王成 on 2017/11/13.
 */
public class RandomUtil {
    private static char[] numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
    private static char[] numbers = ("0123456789").toCharArray();

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String getTokenId() {
        return (DateUtil.formatDate(new Date()) + getUUID() + getRandomStr(4)).toUpperCase();
    }

    public static String getRandomStr(int len) {
        StringBuilder stringBuffer = new StringBuilder();
        for (int i = 0; i < len; i++) {
            stringBuffer.append(getRandomHex());
        }
        return stringBuffer.toString();
    }

    private static String getRandomHex() {
        return Integer.toHexString(new SecureRandom().nextInt(16));
    }

    public static String genSessionId() {
        return getUUID() + getRandomStr(8);
    }

    /* 产生随机字符字符串  */
    public static String randomString(int length) {
        Random strGen = new Random();
        if (length < 1) {
            length = 32;
        }
        char[] randBuffer = new char[length];
        for (int i = 0; i < randBuffer.length; i++) {
            randBuffer[i] = numbersAndLetters[strGen.nextInt(61)];
        }
        return new String(randBuffer);
    }

    /**
     * 随机生成字符及数字的字符串
     *
     * @param length 长度
     * @return 字符串
     */
    public static String randomCharNumberString(int length) {
        String val = "";
        Random random = new Random();
        //参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                //输出大写字母
                val += (char) (random.nextInt(26) + 65);
            } else {
                //输出数字
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    /* 产生随机数值字符串  */
    public static String randomNumStr(int length) {
        Random numGen = new Random();
        if (length < 1) {
            length = 32;
        }
        char[] randBuffer = new char[length];
        for (int i = 0; i < randBuffer.length; i++) {
            randBuffer[i] = numbers[numGen.nextInt(9)];
        }
        return new String(randBuffer);
    }

    public static String getRandomInt() {
        return String.format("%06d", new SecureRandom().nextInt(1000000));
    }
}
